<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .section {
            margin-bottom: 40px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .error {
            color: red;
            margin: 10px 0;
        }
        .success {
            color: green;
            margin: 10px 0;
        }
        button {
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="nav">
            <a href="index.html">用户管理</a>
            <a href="role.html">角色管理</a>
            <a href="menu.html">菜单管理</a>
        </div>
        <div id="errorMessage" class="error"></div>
        <div id="successMessage" class="success"></div>
        
        <!-- 添加用户部分 -->
        <div class="section">
            <h2>添加用户</h2>
            <form id="userForm">
                <div class="form-group">
                    <label for="username">用户名：</label>
                    <input type="text" id="username" required>
                </div>
                <div class="form-group">
                    <label for="email">邮箱：</label>
                    <input type="email" id="email" required>
                </div>
                <div class="form-group">
                    <label for="age">年龄：</label>
                    <input type="number" id="age" required>
                </div>
                <div class="form-group">
                    <label for="password">密码：</label>
                    <input type="password" id="password" required>
                </div>
                <div class="form-group">
                    <label for="userRoles">角色：</label>
                    <select id="userRoles" multiple>
                        <!-- 角色选项将通过 JS 动态添加 -->
                    </select>
                </div>
                <button type="submit">添加用户</button>
            </form>
        </div>

        <!-- 编辑用户部分 -->
        <div class="section" id="editUserSection" style="display: none;">
            <h2>编辑用户</h2>
            <form id="editUserForm">
                <input type="hidden" id="editUserId">
                <div class="form-group">
                    <label for="editUsername">用户名：</label>
                    <input type="text" id="editUsername" required>
                </div>
                <div class="form-group">
                    <label for="editEmail">邮箱：</label>
                    <input type="email" id="editEmail" required>
                </div>
                <div class="form-group">
                    <label for="editAge">年龄：</label>
                    <input type="number" id="editAge" required>
                </div>
                <div class="form-group">
                    <label for="editUserRoles">角色：</label>
                    <select id="editUserRoles" multiple>
                        <!-- 角色选项将通过 JS 动态添加 -->
                    </select>
                </div>
                <button type="submit">更新用户</button>
                <button type="button" id="cancelEditButton">取消</button>
            </form>
        </div>

        <!-- 用户列表部分 -->
        <div class="section">
            <h2>用户列表</h2>
            <table id="userTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>年龄</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <script>
        const API_URL = 'http://localhost:3000/users';
        const errorMessageElement = document.getElementById('errorMessage');
        const successMessageElement = document.getElementById('successMessage');

        function showMessage(message, isError = false) {
            const element = isError ? errorMessageElement : successMessageElement;
            element.textContent = message;
            setTimeout(() => {
                element.textContent = '';
            }, 3000);
        }

        // 获取所有角色
        async function fetchRoles() {
            try {
                const response = await fetch('http://localhost:3000/roles');
                if (!response.ok) {
                    throw new Error('获取角色列表失败');
                }
                const roles = await response.json();
                
                // 更新角色下拉选择
                const roleSelect = document.getElementById('userRoles');
                roleSelect.innerHTML = roles.map(role => 
                    `<option value="${role.id}">${role.name}</option>`
                ).join('');

                // 更新编辑用户角色选择
                const editRoleSelect = document.getElementById('editUserRoles');
                editRoleSelect.innerHTML = roles.map(role => 
                    `<option value="${role.id}">${role.name}</option>`
                ).join('');
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 获取用户列表
        async function fetchUsers() {
            try {
                const response = await fetch(API_URL);
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '获取用户列表失败');
                }
                const users = await response.json();
                const tbody = document.querySelector('#userTable tbody');
                tbody.innerHTML = '';
                
                users.forEach(user => {
                    tbody.innerHTML += `
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>${user.age}</td>
                            <td>${user.roles?.map(role => role.name).join(', ') || '无'}</td>
                            <td>
                                <button onclick="editUser(${user.id})">编辑</button>
                                <button onclick="deleteUser(${user.id})">删除</button>
                            </td>
                        </tr>
                    `;
                });
            } catch (error) {
                showMessage(error.message, true);
                console.error('Error:', error);
            }
        }

        // 添加用户
        document.getElementById('userForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const userData = {
                    username: document.getElementById('username').value,
                    email: document.getElementById('email').value,
                    age: parseInt(document.getElementById('age').value),
                    password: document.getElementById('password').value,
                    roleIds: Array.from(document.getElementById('userRoles').selectedOptions).map(option => parseInt(option.value))
                };

                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(userData)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '添加用户失败');
                }

                document.getElementById('userForm').reset();
                fetchUsers();
                showMessage('添加用户成功！');
            } catch (error) {
                showMessage(error.message, true);
                console.error('Error:', error);
            }
        });

        // 删除用户
        async function deleteUser(id) {
            if (confirm('确定要删除这个用户吗？')) {
                try {
                    const response = await fetch(`${API_URL}/${id}`, {
                        method: 'DELETE'
                    });

                    if (!response.ok) {
                        throw new Error('删除用户失败');
                    }

                    fetchUsers();
                } catch (error) {
                    showMessage(error.message, true);
                }
            }
        }

        // 编辑用户
        async function editUser(id) {
            try {
                const response = await fetch(`${API_URL}/${id}`);
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                const user = await response.json();
                
                // 填充编辑表单
                document.getElementById('editUserId').value = user.id;
                document.getElementById('editUsername').value = user.username;
                document.getElementById('editEmail').value = user.email;
                document.getElementById('editAge').value = user.age;

                // 选择用户角色
                const editRoleSelect = document.getElementById('editUserRoles');
                Array.from(editRoleSelect.options).forEach(option => {
                    option.selected = user.roles.some(role => role.id === parseInt(option.value));
                });

                // 显示编辑表单
                document.getElementById('editUserSection').style.display = 'block';
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 更新用户
        document.getElementById('editUserForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const id = document.getElementById('editUserId').value;
            const updatedUserData = {
                username: document.getElementById('editUsername').value,
                email: document.getElementById('editEmail').value,
                age: parseInt(document.getElementById('editAge').value),
                roleIds: Array.from(document.getElementById('editUserRoles').selectedOptions).map(option => parseInt(option.value))
            };

            try {
                const response = await fetch(`${API_URL}/${id}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(updatedUserData)
                });

                if (!response.ok) {
                    throw new Error('更新用户失败');
                }

                showMessage('用户更新成功！');
                fetchUsers();
                document.getElementById('editUserSection').style.display = 'none'; // 隐藏编辑表单
            } catch (error) {
                showMessage(error.message, true);
            }
        });

        // 取消编辑
        document.getElementById('cancelEditButton').addEventListener('click', () => {
            document.getElementById('editUserSection').style.display = 'none'; // 隐藏编辑表单
        });

        // 初始化
        fetchRoles();
        fetchUsers();
    </script>
</body>
</html> 